package com.XZDP.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.XZDP.dto.Result;
import com.XZDP.dto.UserDTO;
import com.XZDP.entity.Blog;
import com.XZDP.entity.User;
import com.XZDP.service.IBlogService;
import com.XZDP.service.IUserService;
import com.XZDP.utils.Constant.RedisConstant;
import com.XZDP.utils.Constant.SystemConstants;
import com.XZDP.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@RestController
@RequestMapping("/blog")
@Slf4j
public class BlogController {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/{id}")
    public Result getBlogById(@PathVariable("id") Long id) {
        log.info("文章{}", id);
        Blog blog = blogService.getById(id);
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        islike(blog);
        return Result.ok(blog);
    }

    public void islike(Blog blog) {
        //查询点赞状态
        Double score = redisTemplate.opsForZSet().score(RedisConstant.ISBLOG_KEY + blog.getId(), UserHolder.getUser().getId().toString());
        if (score != null) {
            blog.setIsLike(true);
        } else {
            blog.setIsLike(false);
        }
    }

    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        return blogService.saveBlog(blog);
    }


    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        return blogService.likeBlog(id);
    }

    @GetMapping("/likes/{id}")
    public Result likeBlogList(@PathVariable("id") Long id) {
        return blogService.likeBlogList(id);
    }

    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    /**
     * 实现滚动分页查询
     *
     * @param lastId
     * @return
     */
    @GetMapping("/of/follow")
    public Result queryFollowBlog(@RequestParam(value = "lastId") Long lastId, @RequestParam(value = "offset", defaultValue = "0") Integer offset) {
        return blogService.queryFollowBlog(lastId,offset);
    }


    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            if (UserHolder.getUser() != null) {
                islike(blog);
            }
        });
        return Result.ok(records);
    }

    @GetMapping("/of/user")
    public Result queryBlogByUserId(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam("id") Long id) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }
}
